// pages/goods_list/goods_list.js
import { request } from "../../request/index.js"

Page({
  data: {
    tabs: [{
      id: 0,
      value: "综合",
      isActive: true
    }, {
      id: 1,
      value: "销量",
      isActive: false
    }, {
      id: 2,
      value: "价格",
      isActive: false
    }],
    goodsList:[]
  },
  //接口要的参数
  QueryParams:{
    query:"",
    cid:"",
    pagenum:1,
    pagesize:10
  },
  //总页数
  totalPages:1,
  onLoad: function (options) {

    this.QueryParams.cid = options.cid
    this.getGoodsList()

  },
  //根据参数请求商品列表
  async getGoodsList(){
    const {data} = await request({url:"/goods/search",data:this.QueryParams})
    this.setData({
      goodsList:[...this.data.goodsList,...data.message.goods]
    })
    this.totalPages = Math.ceil(data.message.total / this.QueryParams.pagesize)
    // 下拉刷新关闭 如果没有开启 那么关闭也没事
    wx.stopPullDownRefresh()
  },
  //子组件的item被点击事件
  tabsItemChange(e) {
    const { index } = e.detail
    let {tabs} = this.data
    tabs.forEach((v,i) => {
      v.id == index?v.isActive=true:v.isActive=false
    });
    this.setData({
      tabs
    })
  },
  //滚动条触底
  onReachBottom(){
    // 判断有没有下一页数据 当前页码     总页数
    if(this.QueryParams.pagenum >= this.totalPages){
      wx.showToast({ title: '没有更多数据' });
    }else{
      // 还有下一页数据
      //当前的页码++
      //重新请求 然后push 拼接 拼接写到上面
      this.QueryParams.pagenum++
      this.getGoodsList()
    }
  },
  //下拉刷新
  onPullDownRefresh(){
    //重置数组
    this.setData({
      goodsList:[]
    })
    //重置页码
    this.QueryParams.pagenum = 1
    //发送请求
    this.getGoodsList()
  }
  
})